package org.hyn.gateway.socket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import org.hyn.gateway.session.Configuration;
import org.hyn.gateway.session.defaults.DefaultGatewaySessionFactory;
import org.hyn.gateway.socket.handlers.AuthorizationHandler;
import org.hyn.gateway.socket.handlers.GatewayServerHandler;
import org.hyn.gateway.socket.handlers.ProtocolDataHandler;

/**
 * @author franyhu
 * @description 会话管道初始化类
 * 用于配置新连接的通道
 * @date 2025/2/8
 */
public class GatewayChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final Configuration configuration;
    private final DefaultGatewaySessionFactory gatewaySessionFactory;

    public GatewayChannelInitializer(Configuration configuration, DefaultGatewaySessionFactory gatewaySessionFactory) {
        this.configuration = configuration;
        this.gatewaySessionFactory = gatewaySessionFactory;
    }

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        // 入站处理器 (间接继承自 ByteToMessageDecoder)，负责将从客户端接收到的 ByteBuf 数据解码成 HttpRequest 和 HttpContent 对象
        channel.pipeline().addLast(new HttpRequestDecoder());
        // 出站处理器，负责将 HttpResponse 或 HttpContent 对象编码成 ByteBuf 数据，以便发送到客户端
        channel.pipeline().addLast(new HttpResponseEncoder());
        // HttpObjectAggregator 用于处理除了 GET 请求外的 POST 请求时候的对象信息
        channel.pipeline().addLast(new HttpObjectAggregator(1024 * 1024));
        // 自定义的会话处理
        channel.pipeline().addLast(new GatewayServerHandler(configuration));
        channel.pipeline().addLast(new AuthorizationHandler(configuration));
        channel.pipeline().addLast(new ProtocolDataHandler(gatewaySessionFactory));
    }
}
